import irclib
import os
import time
import random
import threading
irclib.DEBUG = True
# Submit a question to lolita3dbot with programd via irc
# To place in a script at the beginning of the game
# we have to connect one time not at each request
# Connection information
#network = 'irc.europnet.org'
network='87.106.99.56'
port = 6667
channel = '#lolita3d'
# All clients must have a different name
nick = 'guest' + str(random.randint(1, 100)) + str(random.randint(1,100))
name = 'guest'

# Generic echo handler ( no space added )
def handlequit ( connection, event ):
	server.connect ( network, port, nick, ircname = name )
	server.join ( channel )
	print 'reconnect... joy !'
	
# Generic echo handler ( no space added )
def handleNoSpace ( connection, event ):
	print event.arguments()[0]
	# delete the " from the event.arguments	
	command = "echo '" +  event.arguments()[0] + "' > receive.txt"
	command = command.replace('"',' ') # strip "
	command = command.replace("'"," ") # strip '
	print 'here is the command i cant see...'	
	print command
	os.system(command)

# Using ctcp to send message
# Generic echo handler ( no space added )
def handlectcp ( connection, event ):
	print 'here is a ctcp philosophy ! tsk ! ...'
	# Send a message	
	if os.path.exists('send.txt'):
		f = open("send.txt", "r")
		text = f.read()
		text = text.replace('"',' ') # strip "
		text = text.replace("'"," ") # strip '
		server.privmsg ('lolita3dbot',text)
		f.close()
		os.remove('send.txt')

# Create the IRC object
irc = irclib.IRC()

# Register handlers
irc.add_global_handler('privmsg', handleNoSpace ) # Private message
irc.add_global_handler('quit', handlequit) # Quit message reconnect
irc.add_global_handler('ctcp', handlectcp) # ctcp ping read message

# Connect to the network
server = irc.server()
server.connect ( network, port, nick, ircname = name )
server.join ( channel )

# Run an infinite loop that scan a rep in thread
irc.process_forever()
